﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Project.MVC.Model;
using Project.MVC.Service;
using Project.MVC.Web.Models.Grid;
using Project.MVC.Web.Helper.jqGrid;
namespace Project.MVC.Web.Areas.QuanLy.Controllers
{
    public class ContactController : Controller
    {
        #region Services
        private readonly IContactServices services;
        public ContactController()
            : this(new ContactServices()
            )
        {
        }

        public ContactController(IContactServices iServices

            )
        {
            services = iServices;

        }
        #endregion
        public ActionResult Index()
        {
            var model = services.GetDefault();
            if (model != null)
                return View("Edit", model);
            else
                return RedirectToAction("Add");


        }
        public ActionResult Add()
        {
            return View("Add");
        }
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Add(ContactInfo lienHe, FormCollection form)
        {
            getInfo(lienHe, form, false);
            services.Insert(lienHe);
            //service.SaveChange();
            return View("Edit", lienHe);
        }
        public ActionResult Edit(int id)
        {
            var model = services.GetDefault();
            return View("Edit", model);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(ContactInfo lienHe, FormCollection form)
        {
            getInfo(lienHe, form, true);
            services.Update(lienHe);
            services.SaveChange();
            return View("Edit", lienHe);
        }
        #region Private methods      
        private void getInfo(ContactInfo value, FormCollection form, bool isUpdate)
        {
            if (form == null) return;
            if (value == null) value = new ContactInfo();
            value.AboutUs = form.Get(ContactInfo.ListFieldName.AboutUs);
            value.Address = form.Get(ContactInfo.ListFieldName.Address);
            value.Company = form.Get(ContactInfo.ListFieldName.Company);
            value.Email = form.Get(ContactInfo.ListFieldName.Email);
            value.Fax = form.Get(ContactInfo.ListFieldName.Fax);
            value.Phone = form.Get(ContactInfo.ListFieldName.Phone);
            value.Yahoo = form.Get(ContactInfo.ListFieldName.Yahoo);
            value.Sky = form.Get(ContactInfo.ListFieldName.Sky);
            value.Sologan = form.Get(ContactInfo.ListFieldName.Sologan);
            if (isUpdate)
            {
                value.Id = int.Parse(form.Get(ContactInfo.ListFieldName.Id));
            }
        }

        #endregion
    }
}
